<template>
	<div class="admin-container">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<el-row :gutter="20">
				<el-col :span="4">
					<el-input v-model="searchParams.name" placeholder="请输入商品名称" clearable
						@keyup.enter.native="searchByName">
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-input v-model="searchParams.pettypeName" placeholder="请输入宠物类型" clearable
						@keyup.enter.native="searchByPettypeName">
					</el-input>
				</el-col>
				<el-col :span="16">
					<el-button type="primary" @click="searchByName">查询商品名称</el-button>
					<el-button type="primary" @click="searchByPettypeName">查询宠物类型</el-button>
					<el-button type="primary" @click="openAddDialog">新增</el-button>
				</el-col>
			</el-row>
		</div>
		<!-- 信息展示区 -->
		<div class="table-container">
			<el-table :data="tableData" style="width: 100%" border v-if="tableData.length > 0"
				@selection-change="handleSelectionChange" ref="multipleTable" :row-class-name="rowClassName"
				:selectable="isRowSelectable">
				<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column prop="name" label="商品名称" width="180"></el-table-column>
				<el-table-column label="宠物图片" width="80">
					<template slot-scope="scope">
						<el-image style="width: 50px; height: 50px;" :src="scope.row.img" fit="cover"></el-image>
					</template>
				</el-table-column>
				<el-table-column prop="description" label="描述"></el-table-column>
				<el-table-column prop="original_price" label="原价" width="80"></el-table-column>
				<el-table-column prop="discount_price" label="折扣价" width="80"></el-table-column>
				<el-table-column prop="pettypeName" label="宠物类型" width="80"></el-table-column>
				<el-table-column prop="stock" label="库存" width="80"></el-table-column>
				<el-table-column prop="state" label="状态" width="80"></el-table-column>
				<el-table-column prop="create_time" label="创建时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.create_time) }}
					</template>
				</el-table-column>
				<el-table-column prop="update_time" label="更新时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.update_time) }}
					</template>
				</el-table-column>
			</el-table>
			<div v-else class="no-data">
				<p>没有找到匹配的数据</p>
			</div>
		</div>
		<!-- 分页组件 -->
		<div class="pagination-container">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page.sync="currentPage" :page-size.sync="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="allData.length"></el-pagination>
		</div>
		<!-- 新增订单对话框 -->
		<el-dialog title="新增订单" :visible.sync="addDialogVisible" width="50%">
			<el-form :model="orderForm">
				<el-form-item label="用户名" label-width="100px">
					<el-input v-model="orderForm.username" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="区域地址" label-width="100px">
					<el-input v-model="orderForm.address_line1" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="详细地址" label-width="100px">
					<el-input v-model="orderForm.address_line2" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="电话" label-width="100px">
					<el-input v-model="orderForm.phone" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" label-width="100px">
					<el-input v-model="orderForm.email" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="订单产品" label-width="100px">
					<el-table :data="orderForm.orderProducts" style="width: 100%">
						<el-table-column prop="name" label="商品名称" width="180"></el-table-column>
						<el-table-column prop="quantity" label="数量"></el-table-column>
						<el-table-column prop="price" label="价格"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button size="mini" @click="removeProduct(scope.row)">移除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
				<el-form-item label="总金额" label-width="100px">
					<el-input v-model="orderForm.total_amount" disabled></el-input>
				</el-form-item>
				<el-form-item label="折扣优惠" label-width="100px">
					<el-input v-model="orderForm.discount" autocomplete="off" type="number" min="0" max="100"
						default="100"></el-input>
				</el-form-item>
				<el-form-item label="支付方式" label-width="100px">
					<el-button type="primary" @click="selectPaymentMethod('微信支付')">微信支付</el-button>
					<el-button type="primary" @click="selectPaymentMethod('支付宝')">支付宝</el-button>
					<el-button type="primary" @click="selectPaymentMethod('现金支付')">现金支付</el-button>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取消</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import axios from 'axios';
	import {
		Input,
		Row,
		Col,
		Button,
		Table,
		TableColumn,
		Dialog,
		Form,
		FormItem,
		Pagination,
		Message,
		Select,
		Option,
		Image as ElImage
	} from 'element-ui';

	export default {
		name: 'ProductTable',
		components: {
			'el-input': Input,
			'el-row': Row,
			'el-col': Col,
			'el-button': Button,
			'el-table': Table,
			'el-table-column': TableColumn,
			'el-dialog': Dialog,
			'el-form': Form,
			'el-form-item': FormItem,
			'el-pagination': Pagination,
			'el-select': Select,
			'el-option': Option,
			'el-image': ElImage
		},
		data() {
			return {
				allData: [], // 存储所有数据
				tableData: [], // 存储当前页的数据
				searchParams: {
					name: '',
					pettypeName: ''
				},
				addDialogVisible: false,
				orderForm: {
				      username: '',
				      address_line1: '',
				      address_line2: '',
				      phone: '',
				      email: '',
				      total_amount: 0,
				      payment_method: '',
				      discount: 100,
				      orderProducts: []
				    },
				selectedRowKeys: [], // 存储所有选中行的ID
				currentPage: 1,
				pageSize: 10
			};
		},
		computed: {
			totalAmount() {
				const discountFactor = this.orderForm.discount / 100;
				return this.orderForm.orderProducts.reduce((sum, product) => {
					return sum + product.quantity * (product.price || 0) * discountFactor;
				}, 0).toFixed(2);
			}
		},
		watch: {
			totalAmount: {
				handler(newVal) {
					this.orderForm.total_amount = parseFloat(newVal);
				},
				immediate: true
			}
		},
		created() {
			this.fetchData();
		},
		methods: {
			fetchData() {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/json',
					'Authorization': token
				};
				axios.get('http://localhost:8887/Product/findAll', {
						headers
					})
					.then(response => {
						if (response.data.code === 200) {
							this.allData = response.data.data;
							this.loadData();
						} else {
							this.$message.error('获取数据失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			loadData() {
				this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this
					.pageSize);
			},
			handleSelectionChange(selection) {
			      // 过滤掉无库存的商品
			      this.selectedRowKeys = selection.filter(row => row.state !== '无库存' && row.stock > 0).map(row => row.id);
			    },
			    rowClassName({ row }) {
			      if (row.state === '无库存' || row.stock <= 0) {
			        return 'no-stock';
			      }
			      return '';
			    },
			searchByName() {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Authorization': token
				};
				axios.get('http://localhost:8887/Product/selectname', {
						headers,
						params: {
							name: this.searchParams.name
						}
					})
					.then(response => {
						if (response.data.code === 200 && response.data.data.length > 0) {
							this.allData = response.data.data;
							this.selectedRowKeys = this.selectedRowKeys.filter(key => {
								return this.allData.some(item => item.id === key);
							});
							this.loadData();
						} else {
							this.$message.error(response.data.message || '未找到匹配的商品');
							this.tableData = [];
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			searchByPettypeName() {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Authorization': token
				};
				axios.get('http://localhost:8887/Product/selectpettype_name', {
						headers,
						params: {
							pettypeName: this.searchParams.pettypeName
						}
					})
					.then(response => {
						if (response.data.code === 200 && response.data.data.length > 0) {
							this.allData = response.data.data;
							this.selectedRowKeys = this.selectedRowKeys.filter(key => {
								return this.allData.some(item => item.id === key);
							});
							this.loadData();
						} else {
							this.$message.error(response.data.message || '未找到匹配的宠物类型');
							this.tableData = [];
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			handleSizeChange(newSize) {
				this.pageSize = newSize;
				this.loadData();
			},
			handleCurrentChange(newPage) {
				this.currentPage = newPage;
				this.loadData();
			},
			openAddDialog() {
				if (this.selectedRowKeys.length === 0) {
					this.$message.error('请选择至少一个商品');
					return;
				}
				this.addDialogVisible = true;
				this.orderForm.orderProducts = this.selectedRowKeys.map(key => {
					const product = this.allData.find(item => item.id === key);
					if (product) {
						return {
							name: product.name,
							product_id: product.id,
							quantity: 1,
							price: product.discount_price || product.original_price,
							discount_price: product.discount_price,
							        original_price: product.original_price,
						};
					} else {
						console.warn('Product with id', key, 'not found in allData');
						return null;
					}
				}).filter(product => product !== null);
				this.orderForm.total_amount = 0; // Reset total amount
			},
			removeProduct(product) {
				const index = this.orderForm.orderProducts.indexOf(product);
				if (index !== -1) {
					this.orderForm.orderProducts.splice(index, 1);
				}
			},
			selectPaymentMethod(method) {
				this.orderForm.payment_method = method;
				this.submitOrder();
			},
			submitOrder() {
			  const token = localStorage.getItem('Authorization');
			  const headers = {
			    'Content-Type': 'application/json',
			    'Authorization': token
			  };
			  axios.post('http://localhost:8887/Order/adminadd', {
			    username: this.orderForm.username,
			    address_line1: this.orderForm.address_line1,
			    address_line2: this.orderForm.address_line2,
			    phone: this.orderForm.phone,
			    email: this.orderForm.email,
			    total_amount: this.orderForm.total_amount,
			    payment_method: this.orderForm.payment_method,
			    orderProducts: this.orderForm.orderProducts
			  }, {
			    headers
			  })
			  .then(response => {
			    if (response.data.code === 200) {
			      this.$message.success('订单添加成功');
			      this.addDialogVisible = false;
			      this.fetchData();
			    } else {
			      this.$message.error('订单添加失败: ' + response.data.message);
			    }
			  })
			  .catch(error => {
			    console.error('请求失败:', error);
			    this.$message.error('请求失败，请检查网络或联系管理员');
			  });
			},
			rowClassName({
				row
			}) {
				if (row.state === '无库存' || row.stock <= 0) {
					return 'no-stock';
				}
				return '';
			},
			isRowSelectable(row) {
				return row.state !== '无库存' && row.stock > 0;
			},
			formatDate(value) {
				const date = new Date(value);
				return new Intl.DateTimeFormat('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				}).format(date);
			}
		}
	};
</script>

<style scoped>
	.admin-container {
		padding: 20px;
		max-width: 100%;
		overflow-x: auto;
	}

	.search-bar {
		margin-bottom: 20px;
	}

	.search-bar .el-row {
		display: flex;
		justify-content: space-between;
	}

	.search-bar .el-button {
		margin-left: 10px;
	}

	.table-container {
		margin-top: 20px;
		overflow-x: auto;
	}

	.no-data {
		text-align: center;
		padding: 20px;
	}

	.pagination-container {
		margin-top: 20px;
		text-align: left;
	}

	.dialog-footer {
		text-align: right;
	}

	.el-dialog__body {
		padding: 20px;
	}

	.el-form-item {
		margin-bottom: 20px;
	}

	.el-form-item__label {
		font-weight: bold;
	}

	.el-button--primary {
		background-color: #13ce66;
		border-color: #13ce66;
	}

	.el-button--primary:hover {
		background-color: #11b55e;
		border-color: #11b55e;
	}

	.no-stock {
		pointer-events: none;
		/* 使行不可点击 */
		color: #ccc;
		/* 文本颜色变淡 */
	}

	.no-stock .el-checkbox {
		display: none;
		/* 隐藏复选框 */
	}
	 .no-stock .el-checkbox__input {
	    display: none; /* 隐藏复选框 */
	  }
</style>